package com.ywh.floating

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import kotlin.math.sqrt

/**
 * Create by yangwenhao on 2022/9/29
 * 通过onTouchListener同时支持拖拽+点击
 */
@SuppressLint("ClickableViewAccessibility")
class TouchHelper(val view: View, private val mTouchSlop: Float, private val actionMove: (movedX: Float, moveY: Float) -> Unit, private val actionUp: () -> Unit, private val actionClick: () -> Unit) {

    init {
        init()
    }

    private var mDownX = 0F
    private var mDownY = 0F
    private var mMoved = false
    private fun init() {
        view.setOnTouchListener { v, event ->
            handleTouchEvent(event)
            true
        }
    }

    private fun handleTouchEvent(event: MotionEvent) {
        //记录当前rawX,rawY
        val rawX = event.rawX
        val rawY = event.rawY
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                mMoved = false
                mDownX = rawX
                mDownY = rawY
            }
            MotionEvent.ACTION_MOVE -> {
                val distanceX = rawX - mDownX
                val distanceY = rawY - mDownY
                if (sqrt((distanceX * distanceX + distanceY * distanceY).toDouble()) > mTouchSlop) {
                    mMoved = true
                    actionMove.invoke(distanceX, distanceY)
                }
            }
            MotionEvent.ACTION_UP -> {
                if (mMoved) {
                    actionUp.invoke()
                    mMoved = false
                } else {
                    actionClick.invoke()
                }
            }
        }
    }

    fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        handleTouchEvent(event)
        return mMoved
    }
}